<template>
  <div class="clientType">
    <global-card>
      <template #leftTitle>
        <perButton label="新建Banner" type="primary" icon="el-icon-plus" perms="PROTOCOL_ADD"
                   @click="newCompanyClick"></perButton>
        <el-button type="success" icon="el-icon-refresh" @click="refresh">刷新</el-button>
      </template>
      <template #content>
        <el-table
          v-loading="loading"
          :data="tableData"
          border
          style="width: 100%"
          class="elTable"
        >
          <el-table-column type="index" label="序号" width="80" align="center"/>
          <el-table-column prop="bannerCode" label="banner编号" align="center"/>
          <el-table-column prop="bannerName" label="Banner名称" align="center"/>
          <el-table-column prop="bannerDesc" label="Banner描述" align="center"/>
          <el-table-column prop="bannerUrl" label="图片" align="center">
            <template #default="{ row }">
              <!--            <viewer :images="imgList">-->
              <!--              <img-->
              <!--                style="height: 200px;width: 200px;"-->
              <!--                v-for="(src,index) in imgList" :src="src" :key="index"-->
              <!--                class="mr-2 mb-2 bg-light h-100 w-100 obj-cover">-->
              <!--            </viewer>-->
              <viewer class="w-100 h-100">
                <img
                  :src="row.bannerUrl"
                  class="w-100 bg-light h-100 obj-cover">
              </viewer>
            </template>
          </el-table-column>
          <el-table-column prop="companyType" label="是否启用" align="center">
            <template slot-scope="scope">
              {{ scope.row.isActive == 1 ? "启用" : "未启用"}}
            </template>
          </el-table-column>

          <el-table-column prop="createByName" label="创建人" align="center"/>
          <el-table-column label="创建时间" align="center" prop="createTime" width="170">
            <template slot-scope="scope">
              {{ scope.row.createTime }}
            </template>
          </el-table-column>
          <el-table-column prop="updateByName" label="更新人" align="center"/>
          <el-table-column label="更新时间" align="center" prop="createTime" width="170">
            <template slot-scope="scope">
              {{ scope.row.updateTime }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" align="center">
            <template #default="{ row }">
              <perButton label="编辑" type="warning" size="mini" perms="PROTOCOL_EDIT"
                         @click="handlerEdit(row)"></perButton>
              <perButton label="删除" type="danger" size="mini" perms="PROTOCOL_DEL"
                         @click="handlerDelete(row)"></perButton>
            </template>
          </el-table-column>
        </el-table>
      </template>
      <template #footer>
        <pagination
          class="pagination"
          :total="count"
          :page.sync="pageIndex"
          :limit.sync="pageSize"
          @pagination="pagination"
        />
      </template>
    </global-card>

    <yc-dialog
      ref="ycDialog"
      :dialogTitle="dialogTitle"
      :centerTitle="dialogCenterTitle"
    >
      <template #content>
        <div class="dialog-content">
          <el-form
            :model="newBannerModel"
            :rules="rules"
            ref="modelRef"
            label-width="110px"
          >
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="Banner名称" prop="bannerName">
                  <el-input v-model="newBannerModel.bannerName"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="Banner描述" prop="bannerDesc">
                  <el-input v-model="newBannerModel.bannerDesc"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="Banner图片" prop="bannerUrl">
                  <el-upload
                    :action="$uploadUrl + upload"
                    class="avatar-uploader"
                    v-model="newBannerModel.bannerUrl"
                    :headers="headers"
                    :show-file-list="false"
                    :on-success="handleLogoSuccess"
                    :before-upload="beforeAvatarUpload"
                  >
                    <img
                      v-if="newBannerModel.bannerUrl"
                      :src="newBannerModel.bannerUrl"
                      class="avatar"
                    />
                    <i
                      v-else
                      class="el-icon-plus avatar-uploader-icon"
                      :class="{ drop: detailsDisabled }"
                    ></i>
                  </el-upload>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="是否启用" prop="isActive">
                  <el-select v-model="newBannerModel.isActive">
                    <el-option
                      v-for="item in companyTypeList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <div class="xqxx">详情页信息</div>
            <el-upload
              :action="$uploadUrl + upload"
              class="avatar-uploader-quill"
              style="display: none;"
              :headers="headers"
              :show-file-list="false"
              :on-success="handleLogoSuccess2"
            >
            </el-upload>
            <quill-editor v-model="newBannerModel.bannerContext"
                          :options="editorOption"
                          class="ql-editor"
                          ref="myQuillEditor"
                          ></quill-editor>
          </el-form>
        </div>
      </template>
      <template #footer>
        <el-button type="primary" :loading="addOrUpdateLoading" @click="dialogSave">确定</el-button>
        <el-button @click="$refs.ycDialog.dialogVisible = false">取消
        </el-button>
      </template>
    </yc-dialog>

    <global-message
      v-if="isGlobalMessageShow"
      @receive="receive"
      :message="message"
    />
  </div>
</template>

<script>
  import { quillEditor, Quill } from "vue-quill-editor"
  import ImageResize from "quill-image-resize-module" //调整图片大小
  Quill.register("modules/imageResize", ImageResize)
  import "quill/dist/quill.core.css"
  import "quill/dist/quill.snow.css"
  import "quill/dist/quill.bubble.css"

  import ycDialog from "@/components/pageDialog"
  import perButton from "@/components/permissionButton"
  import {
    queryPageBanner,
    insertBanner,
    updateBanner,
    deleteBanner
  } from "@/api/basicSetupManagement/banner"
  import { getToken } from "@/utils/auth"

  export default {
    components: {
      ycDialog,
      perButton,
      quillEditor
      // Tinymce
    },
    data() {
      return {
        tableData: [],
        pageIndex: 1,
        pageSize: 10,
        count: 0,
        tableDataItem: {},
        searchForm: {
          agreementName: "",
          agreementType: ""
        },
        isGlobalMessageShow: false,

        dialogCenterTitle: "",
        dialogTitle: "",
        message: "",

        loading: false,
        newBannerModel: {
          id: "",
          bannerName: "",
          bannerDesc: "",
          bannerUrl: "",
          isActive: "",
          bannerContext: ""
        },
        rules: {
          bannerName: [
            { required: true, message: "请输入Banner名称", trigger: "blur" }
          ],
          bannerDesc: [
            { required: true, message: "请输入Banner描述", trigger: "blur" }
          ],
          bannerUrl: [
            { required: true, message: "请选择Banner图片", trigger: "change" }
          ],
          isActive: [
            { required: true, message: "请选择是否启用", trigger: "change" }
          ],
          bannerContext: [{ required: true, message: "请输入详情页信息", trigger: "blur" }]
        },
        companyTypeList: [
          { id: 0, name: "未启用" },
          { id: 1, name: " 启用" }
        ],
        headers: {
          token: getToken()
        },
        upload: "/uploadManager/upload",

        editorOption: {
          placeholder: "",
          quill: "",
          modules: {
            imageResize: { // 调整图片大小配置
              displayStyles: {
                backgroundColor: "black",
                border: "none", // 是否加边框
                color: "white" // 拖拽时，图片右下角尺寸文字颜色
              },
              modules: ["Resize", "DisplaySize", "Toolbar"] // 工具包：允许拖拽、显示尺寸、对齐方式
            },
            toolbar:{
              container:[ // 工具栏配置
                ["bold", "italic", "underline", "strike"],          //加粗，斜体，下划线，删除线
                [{ "size": ["small", false, "large", "huge"] }],    // 字体大小
                [{ "header": [1, 2, 3, 4, 5, 6, false] }],          //几级标题
                [{ "color": [] }, { "background": [] }],            // 字体颜色，字体背景颜色
                [{ "align": [] }],                                  //对齐方式
                [{ "indent": "-1" }, { "indent": "+1" }],           // 缩进
                [{ "list": "ordered" }, { "list": "bullet" }],      //列表
                [{ "script": "sub" }, { "script": "super" }],       // 上下标
                ["blockquote", "code-block"],                       //引用，代码块
                ["clean"],                                          //清除字体样式
                ["image", "video"]                                  //上传图片、上传视频
              ],
              handlers: {
                image: (value) => {
                  if (value) {
                    // 调用element的图片上传组件
                    document.querySelector(".avatar-uploader-quill input").click();
                  } else {
                    this.quill.format("image", false);
                  }
                },
              },
            },

          }
        },
        detailsDisabled: false,
        addOrUpdateLoading: false
      }
    },
    created() {
      this.getData()
    },
    methods: {
      handleLogoSuccess2(id, file) {
        let quill = this.$refs.myQuillEditor.quill;
        // 获取光标所在位置
        let length = quill.getSelection().index;
        // 插入图片，res为服务器返回的图片链接地址
        quill.insertEmbed(length, "image", file.response.object.url);
        // 调整光标到最后
        quill.setSelection(length + 1);
      },

      async searchClick() {
        this.getData()
      },
      async getData() {
        const { agreementName, agreementType } = this.searchForm
        this.loading = true
        const data = await queryPageBanner({
          pageIndex: this.pageIndex,
          pageSize: this.pageSize,
          agreementName: agreementName
        })
        this.tableData = data.object.data
        this.count = data.object.count
        this.loading = false
      },
      pagination(pageItem) {
        this.getData(pageItem.page, pageItem.limit)
      },


      handlerDelete({ id }) {
        this.$confirm("确定删除此数据吗", "删除操作", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "error",
          center: true
        }).then(async () => {
          const { status } = await deleteBanner({
            id,
            isDeleted: 1
          })
          if (status == 200) {
            this.getData()
            this.isGlobalMessageShow = true
            this.message = "success"
          } else {
            this.message = "error"
          }
        })
      },

      // 新建公司
      newCompanyClick() {
        this.dialogCenterTitle = "新建Banner"
        this.dialogTitle = "新建Banner"

        Object.keys(this.newBannerModel).forEach((item) => {
          this.newBannerModel[item] = ""
        })

        this.detailsDisabled = false
        this.addOrUpdateLoading = false
        this.$refs.ycDialog.dialogVisible = true
        if (this.$refs["modelRef"]) {
          this.$refs["modelRef"].clearValidate()
        }
      },
      handlerEdit(row) {
        this.dialogCenterTitle = "编辑Banner"
        this.dialogTitle = "编辑Banner"

        this.newBannerModel = {
          id: row.id,
          bannerName: row.bannerName,
          bannerDesc: row.bannerDesc,
          bannerUrl: row.bannerUrl,
          isActive: row.isActive,
          bannerContext: row.bannerContext
        }

        this.addOrUpdateLoading = false
        this.detailsDisabled = false
        this.$refs.ycDialog.dialogVisible = true
        if (this.$refs["modelRef"]) {
          this.$refs["modelRef"].clearValidate()
        }
      },

      handleLogoSuccess(id, file) {
        this.newBannerModel.bannerUrl = file.response.object.url
      },
      beforeAvatarUpload(file) {
        // const isType = this.fileType.includes(file.type)
        const isLt2M = file.size / 1024 / 1024 < 5

        // if (!isJPG) {
        //   this.$message.error("上传头像图片只能是 JPG 格式!")
        // }
        // if (!isType) {
        //   this.$message.error("上传文件格式有问题！")
        // }
        // if (!isLt2M) {
        //   this.$message.error("上传头像图片大小不能超过 5MB!")
        // }
        // return isJPG && isLt2M
        // return isType && isLt2M
      },

      // timeFormat(date) {
      //   let newDate = /\d{4}-\d{1,2}-\d{1,2}/g.exec(date)
      //   return newDate[0]
      // },

      async dialogSave() {
        this.$refs.modelRef.validate(async (v) => {
          if (v) {
            this.addOrUpdateLoading = true

            if (this.detailsDisabled) {
              // 详情
              this.$refs.ycDialog.dialogVisible = false
            } else if (this.newBannerModel.id) {
              //  编辑
              const { status, message } = await updateBanner({
                ...this.newBannerModel
              })
              if (status == 200) {
                this.$message({
                  message: message,
                  type: "success"
                })
                this.getData()
                this.$refs.ycDialog.dialogVisible = false
              }
            } else {
              const { status, message } = await insertBanner({ ...this.newBannerModel })
              if (status == "200") {
                this.$message({
                  message: message,
                  type: "success"
                })
                this.getData()
                this.$refs.ycDialog.dialogVisible = false
              }
            }
            this.addOrUpdateLoading = false
          }
        })
      },

      receive() {
        this.isGlobalMessageShow = false
      },

      refresh() {
        this.searchForm = {
          agreementName: "",
          agreementType: ""
        }
        this.getData()
      }
    }
  }
</script>

<style lang="scss" scoped>
  .clientType {
    .title-container {
      display: flex;
      justify-content: flex-end;
      margin-right: 20px;

      .left-box {
        display: flex;

        .formClass {
          /*display: flex;*/
          /*margin-right: 20px;*/

          .el-form-item {
            margin-top: 20px;
            margin-bottom: 0;

            .el-input {
              width: 216px;
            }

            .el-select {
              width: 171px;
              margin-left: 10px;
            }

            .el-date-editor {
              width: 336px;
              margin-left: 10px;
            }
          }
        }

        /*.el-button {*/
        /*  // width: 42px;*/
        /*  height: 36px;*/
        /*  margin-top: 20px;*/
        /*}*/
      }
    }
  }

  .xqxx {
    font-family: Source Han Sans CN;
    font-size: 15px;
    font-weight: 600;
    line-height: 21px;
    padding-left: 15px;
    margin-bottom: -12px;
  }
</style>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
    /* cursor: no-drop; */
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

  .drop {
    cursor: no-drop;
  }
</style>
